import React, { useState, useEffect } from "react";
import moment from "moment";
import axios from "axios";
import {
  List,
  Input,
  Button,
  Skeleton,
  Comment,
  Icon,
  message,
} from "antd";
import Emoji from "./Emoji";
import "../static/css/comment.less";
import http from "../config/http";

export default function MyComment(props) {
  const [initLoading, setinitLoading] = useState(false);
  const { TextArea } = Input;
  const [username, setUsername] = useState("");
  const [email, seteMail] = useState("");
  const [msg, setMsg] = useState("");
  const [code, setCode] = useState(""); // 验证码
  const [list, setlist] = useState([]);
  const [replyTo, setReplyTo] = useState(null); // 记录正在回复的评论对象
  const [sendingCode, setSendingCode] = useState(false); // 是否正在发送验证码
  const [codeSent, setCodeSent] = useState(false); // 验证码是否已发送
  const [countdown, setCountdown] = useState(60); // 倒计时
  const [emailForCode, setEmailForCode] = useState(""); // 记录发送验证码时的邮箱
  const [emailValid, setEmailValid] = useState(true); // 邮箱格式有效性

  const emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

  const handleReply = (comment) => {
    setReplyTo(comment);
  };

// 新增用户名转颜色函数
const getColorFromName = (name) => {
  if (!name) return '#8c8c8c'; // 默认灰色
  let hash = 0;
  for (let i = 0; i < name.length; i++) {
    hash = name.charCodeAt(i) + ((hash << 5) - hash);
  }
  // HSL颜色模式，保证颜色明亮且易读
  const h = hash % 360;
  return `hsl(${h}, 70%, 50%)`;
};

// 新增用户名头像组件
const UserAvatar = ({ name }) => {
  if (!name) return null;
  const bgColor = getColorFromName(name);
  const initials = name.split(' ').map(n => n[0]).join('').toUpperCase();
  
  return (
    <div style={{ 
      width: '32px',
      height: '32px',
      borderRadius: '50%',
      backgroundColor: bgColor,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      color: '#fff',
      fontSize: '14px',
      fontWeight: 'bold'
    }}>
      {initials}
    </div>
  );
};

  const renderComment = (item) => (
    <List.Item key={item.id} style={{ display: 'block' }}>
      <Skeleton avatar title={false} loading={item.loading} active>
        <Comment
          author={<a target="_blank">{item.authorName}</a>}
          avatar={(
            // 使用新创建的UserAvatar组件替换原有图片
            <UserAvatar name={item.authorName} />
          )}
          content={
            <div>
              <div dangerouslySetInnerHTML={{ __html: item.contentHtml }} />
              <span style={{ color: "#1890ff", cursor: "pointer" }} onClick={() => handleReply(item)}>回复</span>
            </div>
          }
          datetime={moment(item.createdAt).format("YYYY-MM-DD HH:mm:ss")}
        />
      </Skeleton>
      {item.children && item.children.length > 0 && (
        <List
          dataSource={item.children}
          renderItem={(child) => renderComment(child)}
          style={{ marginLeft: 30 }} // 可选缩进
        />
      )}
    </List.Item>
  );

  const fetchComments = async () => {
    try {
      const res = await http.get(`/tourist/comments/` + props.articleId);
      if (res.code === 1) {
        const commentTree = buildCommentTree(res.data);
        setlist(commentTree);
      }
    } catch (error) {
      console.error("Failed to fetch comments:", error);
    }
  };

  useEffect(() => {
    fetchComments();
  }, [props.articleId]);

  // 构建评论树结构
  function buildCommentTree(comments) {
    const map = {};
    const tree = [];

    comments.forEach(comment => {
      map[comment.id] = { ...comment, children: [] };
    });

    comments.forEach(comment => {
      const parentId = comment.parentId;
      if (parentId && map[parentId]) {
        map[parentId].children.push(map[comment.id]);
      } else {
        tree.push(map[comment.id]);
      }
    });

    return tree;
  }

  // 加载更多
  const loadMore = () => {};

  const onchangeUser = ({ target: { value } }) => {
    setUsername(value);
  };

  const onchangeEmail = ({ target: { value } }) => {
    seteMail(value);
    // 邮箱变更时重置验证码状态
    if (value !== emailForCode) {
      setCodeSent(false);
      setCode("");
    }
    
    // 实时验证邮箱格式
    const isValid = value === "" || emailReg.test(value);
    setEmailValid(isValid);
  };
 
  const onchangeMsg = ({ target: { value } }) => {
    setMsg(value);
  };

  const onchangeCode = ({ target: { value } }) => {
    setCode(value);
  };

  const inputMessage = (val) => {
    let obj = msg + val;
    setMsg(obj);
  };

  // 发送验证码（不等待后端响应）
  const sendVerificationCode = () => {
    if (sendingCode || !email || !emailReg.test(email)) {
      if (!emailReg.test(email) && email) {
        message.error("邮箱格式错误");
      }
      return; // 如果已经在发送中或者邮箱无效，则返回
    }
    
    // 立即更新状态，进入倒计时
    setSendingCode(true);
    setEmailForCode(email);
    setCodeSent(false);
    setCode("");
    
    // 启动倒计时
    let timer = setInterval(() => {
      setCountdown(prev => {
        if (prev <= 1) {
          clearInterval(timer);
          setSendingCode(false);
          return 60;
        }
        return prev - 1;
      });
    }, 1000);
    
    // 不等待后端响应，直接显示提示
    setCodeSent(true);
    message.success("验证码已发送，请查收邮箱");
    
    // 异步发送请求，不等待结果
    http.post("/tourist/code", { userEmail: email })
      .catch(error => {
        console.error("验证码发送失败:", error);
      });
  };

  const handleSubmit = async (parentId = null) => {
    let emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    
    if (username == "") {
      message.warning("昵称不能为空");
      return;
    }
    
    if (!emailReg.test(email)) {
      message.warning("电子邮箱格式错误");
      return;
    }
    
    if (msg == "") {
      message.warning("评论内容不能为空");
      return;
    }
    
    // 限制长度
    if (msg.length > 200) {
      message.warning("评论内容过长");
      return;
    }
    
    if(username.length > 20){
      message.warning("昵称过长");
      return;
    }
    
    // 验证码验证
    if (!codeSent || email !== emailForCode) {
      message.warning("请先发送验证码");
      return;
    }
    
    if (!code) {
      message.warning("请输入验证码");
      return;
    }

    let params = {
      articleId: props.articleId,
      parentId: parentId, // 如果有值，则为子评论
      authorName: username,
      authorEmail: email,
      contentHtml: msg,
      createdAt: moment().format("YYYY-MM-DD HH:mm:ss"),
      code: code // 添加验证码字段
    };

    http.post("/tourist/comment", params).then((res) => {
      if (res.code === 1) {
        message.success("提交成功");
        setUsername("");
        seteMail("");
        setMsg("");
        setCode("");
        fetchComments();
        
        // 清除验证码状态
        setCodeSent(false);
        setEmailForCode("");
      } else {
        message.error(res.message || "评论提交失败");
      }
    }).catch(error => {
      message.error("网络请求失败");
      console.error("Comment submission error:", error);
    });
  };

  return (
    <div className="comment">
      <div className="comment-editor">
        <h4>
          添加新评论 <span className="note">评论长度200限制字符</span>
        </h4>
        
        {/* 用户信息输入区域 - 水平对齐 */}
        <div className="input-group" style={{ 
          display: "flex", 
          flexDirection: "column",
          marginBottom: 20
        }}>
          {/* 昵称和邮箱输入 - 水平排列 */}
          <div style={{ 
            display: "flex", 
            gap: 12,
            marginBottom: 16
          }}>
            <Input
              allowClear
              value={username}
              onChange={onchangeUser}
              placeholder="用户昵称"
              prefix={<Icon type="user" style={{ color: "rgba(0,0,0,.25)" }} />}
            />
            
            <Input
              allowClear
              value={email}
              onChange={onchangeEmail}
              placeholder="电子邮箱（将保密）"
              prefix={<Icon type="mail" style={{ color: "rgba(0,0,0,.25)" }} />}
            />
          </div>

          {/* 验证码输入区域 - 独立成行 */}
          <div style={{ 
            display: "flex", 
            flexDirection: "column",
            width: "100%"
          }}>
            <div style={{ 
              display: "flex", 
              gap: 12,
              width: "100%"
            }}>
              <Input
                value={code}
                onChange={onchangeCode}
                placeholder="请输入验证码"
                style={{ 
                  flex: 1,
                  minHeight: 45,
                  fontSize: 16,
                  padding: "12px 15px",
                  borderRadius: 6,
                  border: "1px solid #d9d9d9"
                }}
                disabled={!codeSent || email !== emailForCode}
              />
              <Button 
                onClick={sendVerificationCode}
                disabled={sendingCode || !email || !emailReg.test(email)}
                loading={sendingCode}
                style={{ 
                  minWidth: 130,
                  height: 45,
                  flexShrink: 0
                }}
              >
                {sendingCode ? `重新发送(${countdown}s)` : "发送验证码"}
              </Button>
            </div>
            
            {/* 状态提示区域 */}
            <div style={{ 
              minHeight: 20,
              display: "flex",
              alignItems: "center",
              marginTop: 4
            }}>
              {codeSent && email === emailForCode && (
                <div style={{ 
                  fontSize: 14, 
                  color: "#52c41a",
                  display: "flex",
                  alignItems: "center"
                }}>
                  <Icon type="check-circle" theme="twoTone" twoToneColor="#52c41a" />
                  <span style={{ marginLeft: 6 }}>验证码已发送</span>
                </div>
              )}
            </div>
          </div>
        </div>
        
        {/* 评论内容输入区域 */}
        <TextArea
          value={msg}
          onChange={onchangeMsg}
          placeholder="输入你的评论..."
          autoSize={{ minRows: 3, maxRows: 5 }}
          style={{ 
            fontSize: 16,
            padding: 15,
            marginBottom: 16
          }}
        />
        
        {replyTo && (
          <div style={{ 
            color: "#faad14", 
            marginBottom: 16
          }}>
            正在回复：{replyTo.authorName}
            <span 
              onClick={() => setReplyTo(null)} 
              style={{ marginLeft: 10, cursor: "pointer" }}
            >
              取消
            </span>
          </div>
        )}
        
        <div className="comment-editor-tool" style={{ marginBottom: 20 }}>
          <Emoji inputMessage={inputMessage} />
          <Button 
            onClick={() => handleSubmit(replyTo ? replyTo.id : null)} 
            type="primary"
            style={{ marginLeft: 12 }}
          >
            提 交
          </Button>
        </div>
      </div>
      
      <List
        className="demo-loadmore-list "
        header={
          <div>
            <span>评论列表：{list.length}</span>
          </div>
        }
        loading={initLoading}
        itemLayout="horizontal"
        loadMore={loadMore}
        dataSource={list}
        renderItem={(item) => renderComment(item)}
      />
    </div>
  );
}